package cn.newtouch.service.impl;

import cn.newtouch.domain.MovieTicket;
import cn.newtouch.domain.User;
import cn.newtouch.feign.MovieTicketFeign;
import cn.newtouch.mapper.UserMapper;
import cn.newtouch.result.JsonResult;
import cn.newtouch.service.IUserService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lqz
 * @since 2022-09-01
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private MovieTicketFeign movieTicketFeign;


    //查询所有电影信息
    @Override
    public JsonResult movies() {
        return movieTicketFeign.list();
    }


    //购票
    @Override
    public JsonResult buy(Long movieId) {
        //判断电影服务的购买操作是否成功，如果失败，那么直接返回JsonResult（里面包含false/true）
        JsonResult jsonResult = movieTicketFeign.buy(1L, movieId);
        if(!jsonResult.isSuccess()){
            return jsonResult;
        }
        // 如果电影服务购买操作成功，就需要扣减相应的余额
        User user = selectById(1L);
        //将Object转BigDecimal类型
        BigDecimal bigDecimal = JsonResult.getBigDecimal(jsonResult.getData());
        //扣减金额
        BigDecimal newDecimal = user.getBalance().subtract(bigDecimal);
        //设置user的余额
        user.setBalance(newDecimal);
        updateById(user);
        //返回购票成功的信息
        return JsonResult.success();
    }


    //观影
    @Override
    public JsonResult watch(Long movieId) {

        return movieTicketFeign.watch(1L,movieId);

    }


    //保存user 需要保存中间表
    @Override
    public boolean insert(User entity) {
        super.insert(entity);
        // 1.查询所有电影票
        JsonResult jsonResult = movieTicketFeign.list();
        // 2.如果是Object 需要转换成list对象集合，需要像下面这样转，用强转要报错
        List<MovieTicket> movieTickets = JSONObject.parseArray(JSONObject.toJSONString(jsonResult.getData()), MovieTicket.class);
        // 3.得到随机数，随便拿一张电影票，
        int i = (int)(Math.random() * movieTickets.size());
        MovieTicket movieTicket = movieTickets.get(i);
        // 4.给用户送电影票
        movieTicketFeign.buy(entity.getId(),movieTicket.getId());

        return true;
    }
}
